package com.hyts.network.task.impl;


import com.hyts.network.error.ConnectionException;
import com.hyts.network.task.AbstractExecutor;
import com.hyts.network.task.AbstractTask;

import java.io.*;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * project-name:gitee-extends-toolbox
 * package-name:com.hyts.ext.network.task.impl
 * author:Libo/Alex
 * create-date:2018-10-27 21:14
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于:SocketTask执行器
 */
public abstract class SocketTaskExecutor extends AbstractExecutor<Object,Object,Socket> {


    /**
     * field-name: logger
     * field-type: Logger
     * description: 日志输出器
     */
    private Logger logger = Logger.getLogger(this.getClass().getName());

    public SocketTaskExecutor(Socket clientModel) {
        super(clientModel);
    }

    public SocketTaskExecutor(AbstractTask<Socket> task) {
        super(task);
    }

    public SocketTaskExecutor() {
        super();
    }


    @Override
    public Object result() {
        return this.run();
    }


    // 可以覆盖override
    public Object run(){
        try (
                ObjectOutputStream outputStream = new ObjectOutputStream(this.getClientModel().getOutputStream());
                ObjectInputStream inputStream = new ObjectInputStream(this.getClientModel().getInputStream());
        ){
            Object result = inputStream.readObject();
            logger.info("接受到客户端信息："+result);
            outputStream.writeObject(deal(result));
            outputStream.flush();
            return result;
        } catch (IOException | ClassNotFoundException e) {
            throw new ConnectionException("读取客户端信息失败！",e);
        }
    }

    public abstract Object deal(Object param);
}
